<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\Seckill\logic;

use think\Db;

/**
 * 业务逻辑
 */
class SeckillLogic
{
    // 获取商品规格组合Html
    public function getGoodsSpecCombi($goodsSpec = [], $aid = 0, $goods_id = 0,$fetch = '')
    {
        if (empty($goodsSpec) || empty($aid)) return "";

        // 规格数量统计
        $goodsSpecCount = [];
        foreach ($goodsSpec as $key => $value) {
            $goodsSpecCount[$key] = count($value);
        }

        // 规格数组排序
        asort($goodsSpecCount);
        $goodsSpecCombi = [];
        foreach ($goodsSpecCount as $key => $value) {
            $goodsSpecCombi[$key] = $goodsSpec[$key];
        }

        // 提取规格数组key键
        $goodsSpecKeys = array_keys($goodsSpecCombi);

        // 数据组合
        $goodsSpecCombi = $this->getGoodsSpecMultipleCombi($goodsSpecCombi);

        // 查询规格信息
        $where = [
            'aid' => $aid,
            'spec_is_select' => 1,
        ];
        // 查询规格名称
        $order = 'spec_mark_id asc, spec_value_id asc';
        $goodsSpecName = Db::name('product_spec_data')->where($where)->order($order)->group('spec_mark_id')->getField('spec_mark_id, spec_name');
        // 查询规格值
        $order = 'spec_value_id desc';
        $goodsSpecValue = Db::name('product_spec_data')->where($where)->order($order)->getField('spec_value_id, spec_value, spec_mark_id');

        // 查询规格价格
        $where = [
            'aid' => $aid,
        ];
        $field = 'spec_value_id, spec_price, spec_stock, spec_sales_num';
        $goodsSpecPrice = Db::name('product_spec_value')->where($where)->order('spec_price asc')->getField($field);

        $where = [
            'aid' => $aid,
            'goods_id' => $goods_id,
        ];
        $seckillGoodsSpec = Db::name('weapp_seckill_product_spec_value')->where($where)->order('seckill_price asc')->getAllWithIndex('spec_value_id');

        // 组合HTML
        $returnHtml  = "<table class='table table-bordered' id='goodsSpecTable' border='1' cellpadding='10' cellspacing='10'><thead><tr style='background-color: #f7f7f7;'>";

        // 显示第一行的数据
        foreach ($goodsSpecKeys as $value) {
            $returnHtml .= "<td><b><span class=''>{$goodsSpecName[$value]}</span></b></td>";
        }
        $returnHtml .= "<td><b>售卖价</b></td>";
        $returnHtml .= "<td><b>总库存</b></td>";
//        $returnHtml .= "<td><b>是否参与</b></td>";
        $returnHtml .= "<td><b>价格设置</b></td>";
        $returnHtml .= "<td><b>库存设置</b></td>";
        $returnHtml .= "</tr></thead><tbody>";

        // 显示第二行开始
        foreach ($goodsSpecCombi as $key => $value_1) {
            $returnHtml .= "<tr>";
            $specKeysName = [];
            foreach ($value_1 as $value_2) {
                $returnHtml .= "<td><span>{$goodsSpecValue[$value_2]['spec_value']}</span></td>";
                $specKeysName[$value_2] = $goodsSpecName[$goodsSpecValue[$value_2]['spec_mark_id']].':'.$goodsSpecValue[$value_2]['spec_value'];
            }

            ksort($specKeysName);
            $pointsSpecKeys = implode('_', array_keys($specKeysName));

            $returnHtml .= "<input type='hidden' name='goodsSpecSet[pointsSpecKeys][]' value='{$pointsSpecKeys}'>";
            $returnHtml .= "<td><strong>￥{$goodsSpecPrice[$pointsSpecKeys]['spec_price']}</strong></td>";
            $returnHtml .= "<td>{$goodsSpecPrice[$pointsSpecKeys]['spec_stock']}</td>";
            // 商品规格ID
            $returnHtml .= "<input type='hidden' name='goodsSpecSet[$pointsSpecKeys][value_id]' value='{$seckillGoodsSpec[$pointsSpecKeys]['value_id']}'>";
            // 是否参与
//            $specJoin = '';
//            if (!empty($seckillGoodsSpec[$pointsSpecKeys]['is_join'])) $specJoin = "checked='true'";
//            $returnHtml .= "<td><label><input class='is-join' type='checkbox' name='goodsSpecSet[$pointsSpecKeys][is_join]' value='1' {$specJoin}> 参与</label></td>";
            // 价格设置
            $returnHtml .= "<td>";
            if ('view' == $fetch){
                $returnHtml .= "<input type='text' class='input-txt w95 seckill-price' name='goodsSpecSet[$pointsSpecKeys][seckill_price]' placeholder='0' value='{$seckillGoodsSpec[$pointsSpecKeys]['seckill_price']}' disabled onkeyup=\"this.value=this.value.replace(/[^\d\.]/g,'');\" onpaste=\"this.value=this.value.replace(/[^\d\.]/g,'');\"><span class='cw-cell-unit'>元</span>";
            }else{
                $returnHtml .= "<input type='text' class='input-txt w95 seckill-price' name='goodsSpecSet[$pointsSpecKeys][seckill_price]' placeholder='0' value='{$seckillGoodsSpec[$pointsSpecKeys]['seckill_price']}' onkeyup=\"this.value=this.value.replace(/[^\d\.]/g,'');\" onpaste=\"this.value=this.value.replace(/[^\d\.]/g,'');\"><span class='cw-cell-unit'>元</span>";
            }
            $returnHtml .= "</td>";
            // 库存设置
            if ('view' == $fetch){
                $returnHtml .= "<td><input type='text' class='input-txt w95 seckill-stock' name='goodsSpecSet[$pointsSpecKeys][seckill_stock]' placeholder='最多{$goodsSpecPrice[$pointsSpecKeys]['spec_stock']}' data-maxstock='{$goodsSpecPrice[$pointsSpecKeys]['spec_stock']}' disabled value='{$seckillGoodsSpec[$pointsSpecKeys]['seckill_stock']}' onkeyup=\"this.value=this.value.replace(/[^\d\,]/g,'');\" onpaste=\"this.value=this.value.replace(/[^\d\,]/g,'');\"><span class='cw-cell-unit'>件</span></td>";
            }else{
                $returnHtml .= "<td><input type='text' class='input-txt w95 seckill-stock' name='goodsSpecSet[$pointsSpecKeys][seckill_stock]' placeholder='最多{$goodsSpecPrice[$pointsSpecKeys]['spec_stock']}' data-maxstock='{$goodsSpecPrice[$pointsSpecKeys]['spec_stock']}' value='{$seckillGoodsSpec[$pointsSpecKeys]['seckill_stock']}' onkeyup=\"this.value=this.value.replace(/[^\d\,]/g,'');\" onpaste=\"this.value=this.value.replace(/[^\d\,]/g,'');\"><span class='cw-cell-unit'>件</span></td>";
            }
            $returnHtml .= "</tr>";
        }
        $returnHtml .= "</tbody>";
        $returnHtml .= "</table>";

        return $returnHtml;
    }

    // 获取商品规格多种组合排序
    private function getGoodsSpecMultipleCombi()
    {
        $goodsSpec = func_get_args();
        $goodsSpec = current($goodsSpec);
        $goodsSpec_1 = array_shift($goodsSpec);
        $result = [];
        foreach ($goodsSpec_1 as $key => $value) {
            $result[] = array($value);
        }
        foreach ($goodsSpec as $key => $value) {
            $result = $this->getGoodsSpecMultipleCombiArray($result, $value);
        }
        return $result;
    }

    // 获取商品规格多种组合排序数组
    private function getGoodsSpecMultipleCombiArray($goodsSpec_1, $goodsSpec_2)
    {
        $result = [];
        foreach ($goodsSpec_1 as $value_1) {
            foreach ($goodsSpec_2 as $value_2) {
                $value = $value_1;
                $value[] = $value_2;
                $result[] = $value;
            }
        }
        return $result;
    }

    //确认收货 秒杀商品 数据处理
    public function confirmOrderHandle($order_id, $users_id)
    {
        $where = [
            'order_id' => $order_id,
            'users_id' => $users_id,
        ];
        $is_seckill_order = Db::name('shop_order')->where($where)->value('is_seckill_order');
        //秒杀没有加购物车功能  所以一个秒杀订单只会存在一个商品
        $orderGood = Db::name('shop_order_details')->where($where)->find();
        if (!empty($orderGood['data'])){
            $data = unserialize($orderGood['data']);
            $goods_id = !empty($data['goods_id']) ? $data['goods_id'] : 0;
            if (!empty($goods_id)){
                $buy_users_count = Db::name('shop_order')->alias('a')
                    ->join('shop_order_details b','a.order_id = b.order_id')
                    ->where('a.is_seckill_order',$is_seckill_order)
                    ->where('b.product_id',$orderGood['product_id'])
                    ->group('b.users_id')->count();
                $update = [
                    'total_order' => Db::Raw('total_order + 1'),
                    'total_money' => Db::Raw('total_money + '.$orderGood['num'] * $orderGood['product_price']),
                    'buy_users_count' => $buy_users_count,
                    'update_time' => getTime()
                ];
                Db::name('weapp_seckill_archives')->where('goods_id',$goods_id)->update($update);
                $sec_update = [
                    'total_order' => Db::Raw('total_order + 1'),
                    'total_money' => Db::Raw('total_money + '.$orderGood['num'] * $orderGood['product_price']),
                ];
                Db::name('weapp_seckill')->where('id',$is_seckill_order)->update($sec_update);
            }
        }
    }

    //订单取消 秒杀商品 数据处理   既要还原秒杀的也要还原原商品的,库存同步
    public function cancelOrderHandle($order_id, $users_id)
    {
        $where = [
            'order_id' => $order_id,
            'users_id' => $users_id,
        ];
        //秒杀没有加购物车功能  所以一个秒杀订单只会存在一个商品
        $orderGood = Db::name('shop_order_details')->where($where)->find();
        if (!empty($orderGood['data'])){
            $data = unserialize($orderGood['data']);
            $goods_id = !empty($data['goods_id']) ? $data['goods_id'] : 0;
            if (!empty($data['value_id'])) {
                //秒杀订单
                $SpecUpData = [
                    'seckill_stock' => Db::raw('seckill_stock+' . ($orderGood['num'])),
                    'seckill_sales_num' => Db::raw('seckill_sales_num-' . ($orderGood['num'])),
                    'update_time' => getTime(),
                ];
                Db::name('weapp_seckill_product_spec_value')->where('value_id', $data['value_id'])->update($SpecUpData);
                $ArcUpData = [
                    'buy_count' => Db::raw('buy_count-' . ($orderGood['num'])),
                    'update_time' => getTime(),
                ];
                Db::name('weapp_seckill_archives')->where('goods_id',$goods_id)->update($ArcUpData);

                $oriSpecUpData = [
                    'spec_stock'     => Db::raw('spec_stock+' . ($orderGood['num'])),
                    'spec_sales_num' => Db::raw('spec_sales_num-' . ($orderGood['num'])),
                    'update_time' => getTime(),
                ];
                Db::name('product_spec_value')->where(['aid'=> $data['product_id'],'spec_value_id'=> $data['spec_value_id']])->update($oriSpecUpData);

                $oriArcUpData = [
                    'stock_count' => Db::raw('stock_count+' . ($orderGood['num'])),
                    'sales_num'   => Db::raw('sales_num-' . ($orderGood['num'])),
                    'sales_all'   => Db::raw('sales_all-' . ($orderGood['num'])),
                    'update_time' => getTime(),
                ];

            } else {
                $ArcUpData = [
                    'stock' => Db::raw('stock+' . ($orderGood['num'])),
                    'buy_count' => Db::raw('buy_count-' . ($orderGood['num'])),
                    'update_time' => getTime(),
                ];
                $oriArcUpData = [
                    'stock_count' => Db::raw('stock_count+' . ($orderGood['num'])),
                    'sales_num'   => Db::raw('sales_num-' . ($orderGood['num'])),
                    'sales_all'   => Db::raw('sales_all-' . ($orderGood['num'])),
                    'update_time' => getTime(),
                ];
            }
            Db::name('weapp_seckill_archives')->where('goods_id', $goods_id)->update($ArcUpData);
            Db::name('archives')->where('aid', $data['product_id'])->update($oriArcUpData);
        }
    }
}
